package com.tbm.console.proj.json;

import com.tbm.console.common.constant.ConsoleConstant;
import com.tbm.console.common.constant.InsUpdDelFlagConstant;
import com.tbm.console.base.controller.BaseController;
import com.tbm.console.proj.entity.LocalUserInfoEntity;
import com.tbm.console.proj.entity.SystemUser;
import com.tbm.console.proj.service.LocalUserInfoService;
import com.tbm.console.proj.service.SystemUserService;
import com.tbm.console.util.DateUtil;
import com.tbm.console.util.PageData;
import com.tbm.console.util.RightsHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;
import java.util.*;

//说明 字符串：LocalUserInfo，作为替换字符串 LOWERLocalUserInfo

@RestController
@Slf4j
public class LocalUserInfoJson extends BaseController{

    @Autowired
    private LocalUserInfoService localUserInfoService;

    @Autowired
    private SystemUserService systemUserService;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/localUserInfo-list/{page}/{size}")
    public Map<String,Object> localUserInfoList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
        long count = localUserInfoService.count(pageData);
        List<LocalUserInfoEntity> localUserInfos = localUserInfoService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", localUserInfos);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/localUserInfo-ins-upd-del")
    public Object localUserInfo(){
        PageData pageData = this.getPageData();
        String result = "success";
        Object nicknameObj = pageData.get("nickname");
        Object userIdObj = pageData.get("userId");
        Object emailObj = pageData.get("email");
        Object passwordObj = pageData.get("password");
        Object belongObj = pageData.get("belong");
        Object developObj = pageData.get("develop");
        Object ftlObj = pageData.get("ftl");
        Object powerObj = pageData.get("powerLevel");
        Integer userId = Integer.valueOf(userIdObj.toString());
        PageData temp = new PageData();
        temp.put("userId", userId);
        List<LocalUserInfoEntity> all = localUserInfoService.findAll(temp);
        LocalUserInfoEntity localUserInfoEntity = null;
        //修改
        if(all.size()==1){
            localUserInfoEntity = all.get(0);
        //新增
        }else{
            localUserInfoEntity = new LocalUserInfoEntity();
        }

        if(null!=userIdObj&&!"".equals(userIdObj.toString())){
            localUserInfoEntity.setUserId(userId);
        }
        if(null!=nicknameObj&&!"".equals(nicknameObj.toString())){
            localUserInfoEntity.setNickname(nicknameObj.toString());

            //修改system-user
            try{
                SystemUser byId = systemUserService.findById(userId);
                byId.setNickname(nicknameObj.toString());
                systemUserService.save(byId);
            }catch (Exception e){
                log.info("跳过保存");
            }
        }
        if(null!=emailObj&&!"".equals(emailObj.toString())){
            localUserInfoEntity.setEmail(emailObj.toString());
        }

        if(null!=developObj&&!"".equals(developObj.toString())){
            localUserInfoEntity.setDevelopPath(developObj.toString());
        }
        if(null!=ftlObj&&!"".equals(ftlObj.toString())){
            localUserInfoEntity.setDevelopFTLPath(ftlObj.toString());
        }
        Iterator shortCutIterable = pageData.keySet().iterator();
        List<String> idsList = new ArrayList<>();
        while (shortCutIterable.hasNext()) {
            String shortCut = shortCutIterable.next().toString();
            if (shortCut.startsWith("checkBoxName_")) {
                String id = shortCut.split("_")[1];
                idsList.add(id);
            }
        }
        try {
            String shortCode = "S"+String.valueOf(RightsHelper.sumRights(idsList.toArray(new String[idsList.size()])));
            localUserInfoEntity.setUserShortCut(shortCode);
        } catch (Exception e) {

        }
        localUserInfoService.save(localUserInfoEntity);

        //修改用户名密码
        if(null!=passwordObj&&!"".equals(passwordObj.toString())){
            SystemUser systemUser = systemUserService.findById(userId);
            String secret = new Md5Hash(passwordObj.toString(), systemUser.getUsername() + systemUser.getSalt()).toString();
            systemUser.setPassword(secret);
            systemUser.setUpdateTime(DateUtil.getID());
            systemUserService.save(systemUser);
            //修改密码强制退出
//            this.getRequest().getSession().removeAttribute(ConsoleConstant.SESSIONUSER);
//            this.getRequest().getSession().removeAttribute(ConsoleConstant.RIGHTS);
//            this.getRequest().getSession().removeAttribute(ConsoleConstant.ROLEID);
//            this.getRequest().getSession().removeAttribute(ConsoleConstant.BUTTONRIGHTS);
//            result = "logout";
        }


        return result;
    }   


    @RequestMapping(value = "/localUserInfo-nickname/{id}")
    public Object localUserNickNameById(@PathVariable("id") Object id){

        log.info(id.toString());
        try {
            Integer param = Integer.valueOf(id.toString());
            PageData pageData = new PageData();
            pageData.put("userId", param);
            List<LocalUserInfoEntity> all = localUserInfoService.findAll(pageData);
            if (all.size() != 1) {
                return "请配置个人信息";
            } else {
                return all.get(0).getNickname();
            }
        } catch (Exception e) {
        }

        return "";

    }
}